package problems.solved;

import java.util.ArrayList;
import java.util.List;

public class Problem74 {
	private static final int[] factorials = {1, 1, 2, 6, 24, 120, 720, 5040, 40320, 362880};
	private static final int LIMIT = 1000000; 
	
	public static void main(String[] args) {
		int count = 0;
		for (int i = 1; i < LIMIT; i++) {
			List<Integer> found = new ArrayList<Integer>();
			found.add(i);
			int current = next(i);
			while (!found.contains(current) && found.size() <= 60) {
				found.add(current);
				current = next(current);
			}
			if (found.size() == 60) {
				count++;
			}
		}
		System.out.println(count); //402
	}
	
	private static int next(int n) {
		int sum = 0;
		for (char c : Integer.toString(n).toCharArray()) {
			sum += factorials[c - 48];
		}
		return sum;
	}
}
